#include "videowidget.h"
#include "camerathread.h"
#include <QPainter>
#include <QImage>

VideoWidget::VideoWidget(QWidget *parent)
    : QWidget{parent}
{
    this->isSuspend = false;
    this->camera_decoder = nullptr;

}
void VideoWidget::startPaint( void){
    // this->curFrame = curFrame;
    if( this->fmt_ctx != nullptr ){
        this->camera_decoder = new cameraThread(fmt_ctx );
        connect(camera_decoder, &cameraThread::newFrame,  this , &VideoWidget::handleNewFrame);
        this->camera_decoder->start();
    }else{
        qDebug()<<"no fmt_ctx";
    }
};

void  VideoWidget:: stopPaint( void ){


    if( this->fmt_ctx != nullptr ){
        avformat_close_input(&this->fmt_ctx);
        this->fmt_ctx = nullptr;
        this->camera_decoder->terminate();
    }
    currentFrame = QImage();
    update();  // 触发重绘清屏

    // if (frame) {
    //     av_frame_free(&frame);
    //     frame = nullptr;
    // }
};


bool isSuspendFrame = false;
void VideoWidget::handleNewFrame(QImage img) {
    this->currentFrame = img;
    if(!this->isSuspend){
      update(); // 触发重绘
      isSuspendFrame = false;
    } else{
        if( !isSuspendFrame  ) {
            this->suspendFrame = img;
            isSuspendFrame = true;
        }
    }
}


void  VideoWidget::paintEvent(QPaintEvent *event)  {
    QPainter painter( this  );
    //painter.drawImage( rect(), this->currentFrame);

    if (!this->currentFrame.isNull() ) {
        painter.drawImage(rect(), currentFrame.scaled(size(), Qt::KeepAspectRatio));
    }
}
